import router from './router'
import store from './store'
import { getToken } from './utils/auth'
import { Message } from 'element-ui'

const whiteList = ['/login', '/register', '/forgetPwd']
const permList = ['/login', '/register', '/logout', '/apply', '/orderList', '/payOrder']

router.beforeEach((to, from, next) => {
    if (getToken()) {
        if (to.path === '/login') {
            next('/apply')
        } else {
            store.dispatch('GetUserInfo').then(() => {
                next()
            }).catch(err => {
                store.dispatch('Logout').then(() => {
                    Message.error('请登录')
                    next('/login')
                })
            })
        }

        // 这边一定要加一个定时器，不然会空值，因为actions是异步操作
        // 可能有更好的方案，目前尚且未发现(可以调用后台来进行监视，这边为了减少和后台的交互，选择在前端进行)
        setTimeout(() => {
            if(permList.indexOf(to.path) === -1) {
                let perm = store.state.login.role
                if (perm !== 'admin' && perm !== 'common') {
                    Message.error('您不满足申请条件')
                    next('/apply')
                }
            }
        }, 500);
    } else {
        if (whiteList.indexOf(to.path) !== -1) next()
        else {
            Message.error('请登录')
            next('/login')
        }
    }
})
